#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
安装
author:cold night
email:wh_linux@126.com
'''


import time
from os import rename
from os import remove
from hashlib import md5
from bottle import template
from bottle import route
from bottle import request
from bottle import response
from setting import pwd, TEMPLATE




def _init_mysql(conn, db_name):
    '''
    初始化mysql数据库
    '''
    cursor = conn.cursor()
    sqlf = open(pwd + r'/doc/blog.sql', 'r')
    sqls = sqlf.read() % (db_name, db_name)
    sql = ''
    for line in sqls.split('\n'):
        if ';' not in line:
            sql += line
        else:
            sql += line
            cursor.execute(sql)
            sql = ''
            conn.commit()


@route('/install/')
def install_blog(step=1):
    '''
    安装程序
    '''
    temp = {}
    temp['title'] = '安装水滴博客系统'
    return template('install.html', temp)


@route('/install/post/', method="POST")
def install_post():
    data = request.POST
    DB_ENGINE = data.get('db_engine', 'mysql')
    DB_HOST = data.get('db_host', 'localhost')
    DB_PORT = int(data.get('db_port', 3306))
    DB_NAME = data.get('db_name')
    DB_USER = data.get('db_user', '')
    DB_PASSWD = data.get('db_passwd', '')
    DB_AUTH = True if  data.get('isauth', 'false') == 'true' else False
    AUTH_DB = data.get('auth_db', 'admin')
    CRYPT_STR = md5(str(time.time())).hexdigest()
    

    # 测试数据库连接
    if DB_ENGINE == 'mongo':
        import pymongo
        if DB_AUTH:
            try:
                conn = pymongo.Connection(DB_HOST, DB_PORT)
            except:
                return {'status':False, 'message':'数据库连接失败,检查主机名和端口'}
            db=conn[AUTH_DB]
            result = db.authenticate(DB_USER, DB_PASSWD)
            if not result:
                return {'status':False,
                        'message':'数据库连接失败,检查用户名密码和验证库是否正确'}
        else:
            try:
                conn = pymongo.Connection(DB_HOST, DB_PORT)
            except:
                return {'status':False, 
                        'message':'数据库连接失败,检查主机名,端口和是否需要验证'}
    elif DB_ENGINE == 'mysql':
        import MySQLdb as mysqldb
        try:
            conn = mysqldb.Connection(host=DB_HOST, port=DB_PORT,
                                      user=DB_USER, passwd=DB_PASSWD)
            _init_mysql(conn, DB_NAME)
        except:
            return {"status":False,
                    'message':'数据库连接失败,检查主机名,端口,用户名和密码'}

    #写入配置文件
    sp = r'%s/model/setting.py' % pwd
    try:
        sf = open(sp, 'w')
    except IOError:
        return {"status":False,
                'message':sp+"配置文件写入失败,查看权限是否配置正确"}
    settingStr = """#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
此文件由安装生成的数据库配置文件,
可以更改此文件来修改数据库连接
author:cold night
email:wh_linux@126.com
'''
# 数据库类型:mysql/mongo
DB_ENGINE = "%s"

# 数据库主机
DB_HOST = "%s"

# 数据库端口
DB_PORT = %d


# 数据库名
DB_NAME = "%s"

#数据库用户
DB_USER = "%s"

#数据库密码
DB_PASSWD = "%s"

# 此项专为mongo设置
# 是否需要验证
DB_AUTH = %s

# 此项转为mongo设置,指定使用哪个库进行认证
AUTH_DB = "%s"

#加密字符串
CRYPT_STR = "%s"

page_size=10
    """ % (DB_ENGINE, DB_HOST, DB_PORT, DB_NAME, DB_USER, 
           DB_PASSWD, DB_AUTH, AUTH_DB, CRYPT_STR)

    sf.write(settingStr)
    sf.close()
    from model.common import get_shell
    from model import model
    
    # 创建管理员
    username = data.get('username', None)
    passwd = data.get('password', None)
    email = data.get('email', None)
    users_dict = dict(username=username, password = passwd, email=email)

    model.create_user(users_dict)
    response.COOKIES['user'] = username
    response.COOKIES['user']['max-age'] = 500
    response.COOKIES['user']['path'] = '/'
    response.COOKIES['shell'] = get_shell(username, passwd)
    response.COOKIES['shell']['max-age'] = 500
    response.COOKIES['shell']['path'] = '/'
    TEMPLATE['user'] = username

    # 写入配置
    BLOG_NAME = data.get('blog_name', None)
    SUBTITLE = data.get('subtitle', None)
    options = dict(BLOG_NAME=BLOG_NAME, SUBTITLE=SUBTITLE, ADMINMAIL=email)

    _id = model.category('未分类')
    print _id

    model.article_post(dict(title="欢迎使用水滴系统进行创作",
                            content = "水滴系统是是使用Python语言编写,同时支持MySQL和MongoDB两种数据库的博客系统,它还很年轻,所以还不完善,欢迎大家提出意见或建议,也可以加入我们,你可以登录后台在后台删除这篇文章开始你的写作旅途!祝您愉快!",
                            tags = ['欢迎'],
                            categories = [_id]))
    
    model.insert_option(options)
    rename(pwd+r'/app/install.py', pwd + r'/app/install.py.bak')
    remove(pwd+r'/app/install.pyc')
    return {'status':True, 'message':'安装成功'}
